package me.itblog.services;

import me.itblog.bean.User;
import org.nutz.dao.Cnd;
import org.nutz.dao.Dao;
import org.nutz.ioc.loader.annotation.Inject;
import org.nutz.ioc.loader.annotation.IocBean;
import org.nutz.lang.Lang;
import org.nutz.lang.random.R;

/**
 * Created by Administrator on 2015/12/1.
 */
@IocBean
public class UserService {
    @Inject
    protected Dao dao;

    public User add(String name, String password) {
        User user = new User();
        user.setName(name.trim().toLowerCase());
        user.setSalt(R.UU16());
        user.setPassword(Lang.md5(Lang.md5(password) + user.getSalt()));
        user.setCreateTime(System.currentTimeMillis());
        user.setUpdateTime(System.currentTimeMillis());
        user = dao.insert(user);
        return user;
    }

    /**
     *  password 已经加密过一次
     * @param username
     * @param password
     * @return
     */
    public User fetch(String username, String password) {
        User user = dao.fetch(User.class, Cnd.NEW().and("name", "=", username));
        if (user == null) {
            return null;
        }

        String _pass = Lang.md5(password + user.getSalt());
        if (!_pass.equalsIgnoreCase(user.getPassword())) {
            user = null;
        }
        return user;
    }

    public User fetch(int id) {
        return dao.fetch(User.class, id);
    }

    public void updatePassword(int userId, String password) {
        User user = fetch(userId);
        if (user == null) {
            return;
        }
        user.setSalt(R.UU16());
        user.setPassword(Lang.md5(password + user.getSalt()));
        user.setUpdateTime(System.currentTimeMillis());
        dao.update(user, "^(password|salt|updateTime)$");
    }

    public int changepwd(User user, String oldPwd, String newPwd) {
        String _pass = Lang.md5(oldPwd + user.getSalt());
        if (!_pass.equalsIgnoreCase(user.getPassword())) {
            return 0;
        } else {
            user.setSalt(R.UU16());
            user.setPassword(Lang.md5(newPwd + user.getSalt()));
            user.setUpdateTime(System.currentTimeMillis());
            dao.update(user, "^(password|salt|updateTime)$");
            return 1;
        }
    }
}
